package com.winai.launcher.manager;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.TextView;

import com.arialyy.aria.core.Aria;
import com.ks.projectbasictools.base.SimpleView;
import com.ks.projectbasictools.utils.LogUtils;
import com.winai.launcher.R;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.DirectoryConstant;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.utils.FileUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.utils.StatusBarUtil;
import com.yhao.floatwindow.FloatActivity;
import com.yhao.floatwindow.FloatWindow;
import com.yhao.floatwindow.MoveType;
import com.yhao.floatwindow.Screen;

import java.io.File;
import java.util.List;

/**
 * 作者：康少
 * 时间：2020/5/27 0027
 * 说明：系统升级确认弹窗
 */
public class UpgradeWindowManager {
    private Context mContext;
    private String mPath;
    private static UpgradeWindowManager mInstance;
    private static final String WINDOW_TAG = "upgrade_float_window_tag";

    private AlphaAnimation showAnim, hideAnim;
    private SimpleView simpleView;
    private TextView tvUpdate;

    public static synchronized UpgradeWindowManager getInstance(Context mContext, String path) {
        if (mInstance == null) {
            synchronized (UpgradeWindowManager.class) {
                if (null == mInstance) {
                    mInstance = new UpgradeWindowManager(mContext.getApplicationContext(), path);
                }
            }
        }
        return mInstance;
    }

    private UpgradeWindowManager(Context mContext, String path) {
        this.mContext = mContext;
        this.mPath = path;
        initTipView();

        showAnim = new AlphaAnimation(0, 1);
        showAnim.setDuration(500);
        hideAnim = new AlphaAnimation(1, 0);
        hideAnim.setDuration(500);
    }

    /**
     * @Desc 初始化提示视图
     */
    private void initTipView() {
        simpleView = new SimpleView(mContext, R.layout.dialog_upgrade);
        tipViewListener(simpleView);

        /*获取状态栏高度，不让状态栏背景与状态栏重合*/
        int statusBarHeight;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            statusBarHeight = StatusBarUtil.getStatusBarHeight(mContext);
        } else {
            statusBarHeight = 0;
        }
        float i = statusBarHeight / 600;

        FloatWindow
                .with(mContext)
                .setView(simpleView)
                .setTag(WINDOW_TAG)
                .setWidth(Screen.width, 1.0f) //设置悬浮控件宽高
                .setHeight(Screen.height, 1.1f)
                .setX(0)
                .setY(0)
                .setGravity(Gravity.BOTTOM | Gravity.START)
                .setDesktopShow(false) //桌面显示
                .setMoveType(MoveType.inactive, 0, 0)
                .setFilter(true, FloatActivity.class)/*这行代码必须要有，类名可以是任意类*/
                .build();
    }

    private void tipViewListener(View simpleView) {
        tvUpdate = simpleView.findViewById(R.id.tv_update);
        tvUpdate.setOnClickListener(v -> {
            if (mPath == null) {
                ToastKs.show(mContext, "更新文件为空，请联系后台管理员");
                return;
            }
            boolean fileExists = FileUtils.isFileExists(new File(FileUtils.getLocalPath(mPath)));
            LogUtils.d("系统更新文件是否存在 fileExists = " + fileExists);
            if (!fileExists) {
                downloadFile(mPath);
            } else {
                GlobalPublisher.Notify(GlobalPublisher.DOWNLOAD_ROM_COMPLETE, mPath);
            }
            dismissTip();
        });
    }

    /**
     * @Desc 展示引导提示蒙层
     */
    public void showTip() {
        if (FloatWindow.get(WINDOW_TAG) != null && !FloatWindow.get(WINDOW_TAG).isShowing()) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    FloatWindow.get(WINDOW_TAG).show();
                    //通知QQ音乐暂停
                    NotifyReceiverUtils.notifyControlQQMusic(mContext, Constant.MediaControllerStop, null);
                    //禁止唤醒
                    NotifyReceiverUtils.notifyToggleWakeUpReceiver(mContext, false);
                    //禁止下拉
                    NotifyReceiverUtils.notifyPulldownReceiver(mContext, false);
                    //通知艾益生的视频暂停
                    sendPauseVideo();
                    //关闭曲艺
                    VideoManager.getInstance(mContext).stop(true);
                }
            }, 500);
            simpleView.startAnimation(showAnim);
        }
    }

    /**
     * @Desc 关闭引导提示蒙层
     */
    public void dismissTip() {
        if (FloatWindow.get(WINDOW_TAG) != null && FloatWindow.get(WINDOW_TAG).isShowing()) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    FloatWindow.get(WINDOW_TAG).hide();
                }
            }, 500);
            simpleView.startAnimation(hideAnim);
        }
    }

    private void downloadFile(String path) {
        /**文件数量大于两个时，删除文件夹下所有内容*/
        List<File> fileList = FileUtils.getFile(new File(DirectoryConstant.ROM_PATH));
        if (fileList != null && fileList.size() > 2) {
            FileUtils.deleteFiles(DirectoryConstant.ROM_PATH);
        }
        long taskId = Aria.download(this)
                .load(path)     //读取下载地址
                .setFilePath(FileUtils.getLocalPath(path)) //设置文件保存的完整路径
                .ignoreFilePathOccupy()
                .create();   //创建并启动下载
    }

    /**
     * @date 2020/9/18
     * @desc 通知艾益生视频暂停
     */
    private void sendPauseVideo() {
        String ACTION_PLAY_CONTROL_COMMAND = "com.aiyisheng.speaker.PLAY_CONTROL_COMMAND";
        Intent intent = new Intent();
        intent.setAction(ACTION_PLAY_CONTROL_COMMAND);
        intent.putExtra("command", "DUI.MediaController.Pause");
        intent.putExtra("data", "");
        mContext.sendBroadcast(intent);
    }
}
